<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>业主管理</title>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/axios-interceptors.js"></script>
    <script src="../js/vue3.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link href="../css/index.css" rel="stylesheet"/>
    <style>
        body {
            background-color: #fff;
            padding: 20px;
            font-family: "Microsoft YaHei", sans-serif;
            margin: 0;
        }

        .owner-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 16px;
        }

        .el-button {
            border-radius: 4px;
            transition: all 0.3s;
        }

        .el-button--primary {
            background-color: #409eff;
            border-color: #409eff;
            color: #fff;
        }

        .el-button--primary:hover {
            background-color: #3a8ee6;
            border-color: #3a8ee6;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        }

        .el-button--danger {
            background-color: #f56c6c;
            border-color: #f56c6c;
            color: #fff;
        }

        .el-button--danger:hover {
            background-color: #f78989;
            border-color: #f78989;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
        }

        .el-table {
            border-radius: 8px;
            overflow: hidden;
            background-color: #fff;
            color: #333;
        }

        .el-table th {
            background-color: #fff;
            color: #333;
            font-weight: 500;
            border-bottom: 1px solid #e5e9ef;
        }

        .el-table td {
            border-bottom: 1px solid #e5e9ef;
        }

        .el-table--striped .el-table__body tr.el-table__row--striped td {
            background-color: #fafafa;
        }

        /* 编辑按钮样式 */
        .edit-btn {
            background-color: #409eff;
            color: #fff;
            border-radius: 6px;
            padding: 6px 16px;
            margin-right: 10px;
            transition: background-color 0.3s;
            font-size: 14px; /* 可根据需要调整字体大小 */
        }

        .edit-btn:hover {
            background-color: #3a8ee6;
        }

        /* 删除按钮样式 */
        .delete-btn {
            background-color: #f56c6c;
            color: #fff;
            border-radius: 6px;
            padding: 6px 16px;
            transition: background-color 0.3s;
            font-size: 14px; /* 可根据需要调整字体大小 */
        }

        .delete-btn:hover {
            background-color: #f78989;
        }

        /* 分页组件样式 */
        .el-pagination {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            margin-top: 16px;
            font-size: 16px;
            gap: 15px;
        }

        .el-pagination__total {
            color: #666;
            font-size: 16px;
        }

        .el-pagination__item {
            border-radius: 4px;
            margin: 0 4px;
            width: 36px;
            height: 36px;
            line-height: 36px;
            font-size: 16px;
        }

        .el-pagination__item:focus,
        .el-pagination__item:hover {
            color: #409eff;
            border-color: #409eff;
        }

        .el-pagination__item.active {
            background-color: #409eff;
            border-color: #409eff;
            color: #fff;
        }

        .el-pagination__jump {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .el-pagination__jump input {
            width: 60px;
            height: 36px;
            font-size: 16px;
            text-align: center;
            border-radius: 4px;
            border: 1px solid #dcdfe6;
        }

        .el-pagination__prev,
        .el-pagination__next {
            width: 36px;
            height: 36px;
            line-height: 36px;
            font-size: 18px;
        }

        .el-pagination__sizes {
            font-size: 16px;
        }

        .el-pagination__sizes .el-select .el-input {
            width: 100px;
        }

        .el-pagination__sizes .el-select .el-input__inner {
            height: 36px;
            font-size: 16px;
        }
    </style>
</head>
<body>
<div id="app" class="owner-container">
    <div class="btn-group">
        <el-button type="primary" @click="showAddOwnerDialog">新增业主</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
    </div>
<!--  表单列表  -->
    <div>
        <el-table
                :data="owners"
                border
                stripe
                @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="编号" prop="id" width="80" align="center"></el-table-column>
            <el-table-column label="名称" prop="name" min-width="150"></el-table-column>
            <el-table-column label="电话" prop="telephone" min-width="150"></el-table-column>
            <el-table-column label="性别" prop="gender" min-width="80" align="center">
                <template #default="scope">
                    <el-tag v-if="scope.row.gender === 1" type="error" size="small">男</el-tag>
                    <el-tag v-else type="success" size="small">女</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="身份证" prop="idcard" min-width="180"></el-table-column>
            <el-table-column label="备注" prop="remark" min-width="150"></el-table-column>
            <el-table-column align="center" label="操作" width="200">
                <template #default="scope">
                    <el-button class="edit-btn" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button class="delete-btn" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--  分页组件  -->
        <div style="margin-top: 16px;">
            <el-pagination
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[5,10,15]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            ></el-pagination>
        </div>
    </div>




<!--  编辑弹窗  -->
    <div>
        <el-dialog v-model="dialogVisible"
                   :title="dialogTitle"
                   :before-close="closeDialog"
                   width="500px">
            <el-form :model="ownerForm" label-width="100px" ref="ownerFormRef" :rules="ownerRules">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="ownerForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="telephone">
                    <el-input v-model="ownerForm.telephone"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="ownerForm.gender">
                        <el-radio :value="1">男</el-radio>
                        <el-radio :value="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="身份证" prop="idcard">
                    <el-input v-model="ownerForm.idcard"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="ownerForm.remark" type="textarea" rows="3"></el-input>
                </el-form-item>
                <el-form-item label="所属房间" prop="room">
                    <el-select v-model="ownerForm.houseId" placeholder="请选择所属房间" style="width: 60%" size="default">
                        <el-option v-for="h in houses" :label="h.houseNo" :value="h.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitOwnerForm">提交</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</div>

<script>
    const { createApp, ref, onMounted } = Vue;
    const { ElMessage, ElMessageBox } = ElementPlus;

    const app = createApp({
        setup() {
            // 分页参数
            const pageNum = ref(1);
            const pageSize = ref(10);
            const total = ref(0);
            // 业主列表数据
            const owners = ref([]);
            // 弹窗显示控制
            const dialogVisible = ref(false);
            // 弹窗标题（新增/编辑）
            const dialogTitle = ref('新增业主');
            // 当前编辑的业主ID
            const currentEditId = ref(null);
            //表单数据的houses
            const houses = ref([]);
            // 表单数据
            const ownerForm = ref({
                name: '',
                telephone: '',
                gender: '',
                idcard: '',
                remark: '',
                room: '',
                houseId:''
            });
            // 表单引用
            const ownerFormRef = ref(null);
            // 表单验证规则
            const ownerRules = ref({
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '名称长度在2到20个字符之间', trigger: 'blur' }
                ],
                telephone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'blur' }
                ],
                idcard: [
                    { required: true, message: '请输入身份证', trigger: 'blur' },
                    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
                ],
                room: [
                    { required: true, message: '请选择房屋ID', trigger: 'blur' }
                ]
            });
            // 批量选择的数据
            const multipleSelection = ref([]);


            //显示新增业主弹窗
            const showAddOwnerDialog = () => {
                ownerForm.value = {
                    id: '',
                    name: '',
                    telephone: '',
                    gender: '',
                    idcard: '',
                    remark: '',
                    room: ''
                };
                initSelect();
                dialogVisible.value = true;
            };


            //处理编辑操作
            const handleEdit = (row) => {
                axios.get("/house/getHouseNoAndId").then(resp => {
                    houses.value = resp.data.obj; // 填充下拉框选项
                    ownerForm.value = {
                        id: row.id,
                        name: row.name,
                        telephone: row.telephone,
                        gender: row.gender,
                        idcard: row.idcard,
                        remark: row.remark,
                        room: row.room
                    };
                    initSelect();
                    dialogVisible.value = true;
                })
            };

            // 清空校验红字信息
            const clearValid = () => {
                if (ownerFormRef && ownerFormRef.value) {
                    ownerFormRef.value.resetFields();
                }
            }

            //编辑弹窗的取消方法
            const closeDialog = () => {
                clearValid();
                ownerForm.value = {};
                dialogVisible.value = false;
            }

            //处理单个删除操作
            const handleDelete = (row) => {
                ElMessageBox.confirm('将永久删除该电影信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        axios.delete(`/owner/deleteById/${row.id}`)
                            .then((resp) => {
                                if (resp.data.obj === 1) {
                                    getOwnerList()
                                    ElMessage.success('删除成功')
                                }
                            })
                            .catch(error => {
                                ElMessage.error(error.response.data.msg)
                            })
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消删除',
                        })
                    })
            };

            //处理选择项变化
            const handleSelectionChange = (val) => {
                multipleSelection.value = val;
                console.log('已选择的项:', multipleSelection.value);
            };

            //批量删除选中的业主
            const batchDelete = () => {
                if (multipleSelection.value.length === 0) {
                    ElMessage.warning("请选择需要删除的业主");
                    return;
                }

                ElMessageBox.confirm('将永久删除选中的业主信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    // 提取选中项的id列表
                    const ids = multipleSelection.value.map(item => item.id);
                    axios.delete("/owner/deleteByIds", { data: ids })
                        .then((resp) => {
                            if (resp.data.obj === 1) {
                                getOwnerList();
                                ElMessage.success("删除成功");
                                multipleSelection.value = [];
                            } else {
                                ElMessage.error("删除失败，请稍后再试");
                            }
                        })
                        .catch(error => {
                            console.log(error);
                            ElMessage.error("批量删除出错，请稍后再试");
                        });
                }).catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消批量删除',
                    });
                });
            };


            //提交表单（新增或编辑）
            const submitOwnerForm = () => {
                //判断校验是否通过
                if (ownerFormRef.value.validate(valid => {
                    if (valid) {
                        //校验通过
                        if (!ownerForm.value.id || ownerForm.value.id === '') {
                            // 新增操作
                            axios.post("/owner/insertOwner", ownerForm.value)
                                .then((resp) => {
                                    if (resp.data.obj === 1) {
                                        ElMessage.success("添加成功")
                                        dialogVisible.value = false
                                        getOwnerList()
                                    }
                                })
                                .catch(error => {
                                    ElMessage.error(error.response.data.msg)
                                })
                        } else {
                            // 修改操作
                            axios.put("/owner/updateOwner", ownerForm.value)
                                .then((resp) => {
                                    if (resp.data.obj === 1) {
                                        console.log("修改成功")
                                        ElMessage.success("修改成功")
                                        dialogVisible.value = false
                                        getOwnerList()
                                    }
                                })
                                .catch(error => {
                                    ElMessage.error(error.response.data.msg)
                                })
                        }
                    } else {
                        //校验不通过
                        ElMessage.error("请输入完整信息")
                    }
                })) ;

            };

            // 处理分页大小变化（更新每页显示条数）
            const handleSizeChange = (val) => {
                pageSize.value = val
                getOwnerList()
            };

            // 处理分页页码变化（更新当前页码）
            const handleCurrentChange = (val) => {
                pageNum.value = val
                getOwnerList()
            };


            // 获取业主列表
            const getOwnerList = () => {
                console.log('加载业主数据')
                axios.get(`/owner/${pageNum.value}/${pageSize.value}`)
                    .then(resp=>{
                        owners.value=resp.data.obj.data
                        total.value=resp.data.obj.total
                    })
                    .catch((error)=>{
                        ElMessage.error(error.response.data.msg)
                    })
            };

            // 发送请求查询房间下拉框的所需数据
            const initSelect=()=>{
                axios.get("/house/getHouseNoAndId").then(resp => {
                    houses.value = resp.data.obj;
                })
            }

            // 页面加载时获取数据
            onMounted(() => {
                getOwnerList();
                initSelect();
            })

            return {
                owners,
                pageNum,
                pageSize,
                total,
                houses,
                dialogVisible,
                dialogTitle,
                ownerForm,
                ownerFormRef,
                ownerRules,
                multipleSelection,
                showAddOwnerDialog,
                handleEdit,
                handleDelete,
                batchDelete,
                submitOwnerForm,
                handleSelectionChange,
                handleSizeChange,
                handleCurrentChange,
                getOwnerList,
                closeDialog,
                clearValid,
                initSelect,
            };
        }
    });

    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });

    app.mount('#app');
</script>
</body>
</html>